<template>
	<view class="group-buy-detail-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left">
				<uni-icons type="left" size="20" @click="goBack"></uni-icons>
			</view>
			<view class="navbar-title">详情</view>
			<view class="navbar-right">
				<uni-icons type="more-filled" size="20" @click="showMoreOptions"></uni-icons>
				<uni-icons type="location" size="20" @click="showLocation" style="margin-left: 8px;"></uni-icons>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
		</view>
		
		<!-- 商品图片轮播 -->
		<view v-else-if="productDetail" class="product-images">
			<swiper class="image-swiper" indicator-dots autoplay circular>
				<swiper-item v-for="(image, index) in productImages" :key="index">
					<image :src="image" mode="aspectFill" class="product-image"></image>
				</swiper-item>
			</swiper>
		</view>
		
		<!-- 商品基本信息 -->
		<view v-if="productDetail" class="product-info">
			<view class="product-title">{{ productDetail.title }}</view>
			<view class="product-meta">
				<view class="publisher">{{ productDetail.merchantName }}</view>
				<view class="publish-time">{{ formatTime(productDetail.startTime) }}</view>
			</view>
		</view>
		
		<!-- 活动描述 -->
		<view v-if="productDetail" class="activity-description">
			<view class="description-text">
				{{ productDetail.description }}
			</view>
		</view>
		
		<!-- 价格信息 -->
		<view v-if="productDetail" class="price-info">
			<view class="price-section">
				<text class="price-label">价格:</text>
				<text class="current-price">¥{{ productDetail.groupPrice }}.00</text>
			</view>
			<view v-if="productDetail.originalPrice" class="price-section">
				<text class="price-label">原价:</text>
				<text class="original-price">¥{{ productDetail.originalPrice }}.00</text>
			</view>
			<view v-if="productDetail.discount > 0" class="price-section">
				<text class="price-label">优惠:</text>
				<text class="discount-text">{{ productDetail.discount }}%</text>
			</view>
		</view>
		
		<!-- 活动详情 -->
		<view v-if="productDetail" class="activity-details">
			<view class="detail-item">
				<text class="detail-label">截止日期:</text>
				<text class="detail-value">{{ formatTime(productDetail.endTime) }}</text>
			</view>
			<view class="detail-item">
				<text class="detail-label">咨询电话:</text>
				<text class="detail-value">{{ productDetail.contactPhone || '暂无' }}</text>
				<text class="debug-info" v-if="showDebug">(字段: contactPhone)</text>
			</view>
			<view class="detail-item">
				<text class="detail-label">注意事项:</text>
				<text class="detail-value">{{ productDetail.terms || '暂无' }}</text>
				<text class="debug-info" v-if="showDebug">(字段: terms)</text>
			</view>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="bottom-actions">
			<view class="action-left">
				<view class="action-item" @click="toggleFavorite">
					<uni-icons :type="isFavorite ? 'heart-filled' : 'heart'" size="20" :color="isFavorite ? '#ff4757' : '#666'"></uni-icons>
					<text class="action-text">收藏</text>
				</view>
				<view class="action-item" @click="contactService">
					<uni-icons type="chatbubble" size="20" color="#666"></uni-icons>
					<text class="action-text">客服</text>
				</view>
			</view>
			<view class="action-right">
				<view class="join-btn" @click="joinGroup" :class="{ 'disabled': !productDetail || productDetail.status !== 'active' }">
					<text class="btn-text">{{ getJoinButtonText() }}</text>
				</view>
			</view>
		</view>
		
		<!-- 错误提示 -->
		<view v-if="error" class="error-container">
			<text class="error-text">{{ error }}</text>
			<view class="retry-btn" @click="loadProductDetail">重试</view>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	import uniLoadMore from '@dcloudio/uni-ui/lib/uni-load-more/uni-load-more.vue';
	import { groupPurchaseApi } from '@/api/index.js';
	
	export default {
		components: { 
			uniIcons,
			uniLoadMore
		},
		data() {
			return {
				isFavorite: false,
				loading: false,
				error: null,
				productDetail: null,
				showDebug: false, // 调试开关
				loadingText: {
					contentdown: '上拉显示更多',
					contentrefresh: '正在加载...',
					contentnomore: '没有更多数据了'
				}
			};
		},

		computed: {
			productImages() {
				if (!this.productDetail || !this.productDetail.image) {
					return ['/static/c1.png']; // 默认图片
				}
				// 如果图片是数组，直接使用；如果是字符串，转换为数组
				if (Array.isArray(this.productDetail.image)) {
					return this.productDetail.image;
				}
				// 如果是逗号分隔的字符串，分割成数组
				if (typeof this.productDetail.image === 'string' && this.productDetail.image.includes(',')) {
					return this.productDetail.image.split(',').map(img => img.trim());
				}
				// 单个图片
				return [this.productDetail.image];
			}
		},

		onLoad(options) {
			if (options.productid) {
				this.loadProductDetail(options.productid);
			} else if (options.productId) {
				this.loadProductDetail(options.productId);
			} else {
				this.error = '缺少商品ID参数';
			}
		},
		
		methods: {
			// 返回上一页
			goBack() {
				const pages = getCurrentPages();
				if (pages.length > 1) {
					uni.navigateBack();
				} else {
					uni.reLaunch({
						url: '/pages/GroupBuy/GroupBuy'
					});
				}
			},
			
			// 显示更多选项
			showMoreOptions() {
				uni.showActionSheet({
					itemList: ['分享', '举报', '收藏'],
					success: (res) => {
						console.log('选择了:', res.tapIndex);
						// TODO: 处理选项
					}
				});
			},
			
			// 显示位置信息
			showLocation() {
				uni.showToast({
					title: '位置功能开发中',
					icon: 'none'
				});
			},
			
			// 切换调试模式
			toggleDebug() {
				this.showDebug = !this.showDebug;
				console.log('调试模式:', this.showDebug ? '开启' : '关闭');
				if (this.showDebug) {
					console.log('当前产品详情:', this.productDetail);
				}
			},
			
			// 加载商品详情
			async loadProductDetail(productId) {
				this.loading = true;
				this.error = null;
				
				try {
					console.log('开始加载团购详情，ID:', productId);
					
					// 使用新的API接口获取团购详情
					const result = await groupPurchaseApi.getGroupPurchaseDetail(productId);
					
					console.log('API返回结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 检查API响应
					if (result && result.code === 200 && result.data) {
						// 转换后端数据格式
						this.productDetail = this.convertBackendData(result.data);
						console.log('团购详情加载成功:', this.productDetail);
					} else {
						this.error = result?.msg || '获取团购详情失败';
						console.error('团购详情加载失败:', result?.msg);
					}
				} catch (error) {
					this.error = '网络错误，请检查网络连接';
					console.error('加载团购详情时发生错误:', error);
				} finally {
					this.loading = false;
				}
			},
			
			// 转换后端数据格式
			convertBackendData(backendData) {
				console.log('开始转换后端数据，原始数据:', backendData);
				
				// 调试：打印所有可用的字段
				console.log('后端数据所有字段:', Object.keys(backendData));
				console.log('后端数据完整内容:', backendData);
				
				const converted = {
					id: backendData.id || backendData.groupPurchaseId,
					title: backendData.title || backendData.groupName || '团购活动',
					description: backendData.content || backendData.description || '暂无描述',
					groupPrice: backendData.presentPrice || backendData.currentPrice || 0,
					originalPrice: backendData.originalPrice || backendData.oldPrice || 0,
					discount: this.calculateDiscount(backendData.originalPrice, backendData.presentPrice),
					image: backendData.img || backendData.image || '/static/c1.png',
					merchantId: backendData.publisherId || backendData.merchantId,
					merchantName: backendData.publisher || backendData.merchantName || '未知商家',
					location: backendData.location || '未知位置',
					startTime: backendData.time || backendData.startTime || new Date().toISOString(),
					endTime: backendData.endTime || backendData.endTime || new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
					minParticipants: backendData.minParticipants || 2,
					maxParticipants: backendData.maxParticipants || 10,
					currentParticipants: backendData.currentParticipants || 0,
					status: this.mapStatus(backendData.status || 'active'),
					serviceType: this.mapServiceType(backendData.title || ''),
					// 尝试多种可能的字段名
					contactPhone: backendData.telephone || backendData.contactPhone || backendData.phone || backendData.contact || backendData.phoneNumber || '暂无',
					terms: backendData.note || backendData.terms || backendData.notes || backendData.notice || backendData.attention || '暂无'
				};
				
				console.log('转换后的数据:', converted);
				return converted;
			},
			
			// 计算折扣
			calculateDiscount(originalPrice, presentPrice) {
				if (!originalPrice || !presentPrice || originalPrice <= 0) return 0;
				return Math.round(((originalPrice - presentPrice) / originalPrice) * 100);
			},
			
			// 映射状态
			mapStatus(status) {
				const statusMap = {
					'active': 'active',
					'inactive': 'inactive',
					'pending': 'pending',
					'completed': 'completed',
					'cancelled': 'cancelled'
				};
				return statusMap[status] || 'active';
			},
			
			// 映射服务类型
			mapServiceType(title) {
				if (title.includes('洗车')) return 'carwash';
				if (title.includes('保养')) return 'maintenance';
				if (title.includes('维修')) return 'repair';
				if (title.includes('救援')) return 'rescue';
				if (title.includes('钣喷')) return 'painting';
				return 'other';
			},
			
			// 格式化时间
			formatTime(timeString) {
				if (!timeString) return '暂无';
				
				try {
					const date = new Date(timeString);
					if (isNaN(date.getTime())) return '时间格式错误';
					
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					
					return `${year}/${month}/${day} ${hours}:${minutes}`;
				} catch (error) {
					console.error('时间格式化错误:', error);
					return '时间格式错误';
				}
			},
			
			// 获取报名按钮文本
			getJoinButtonText() {
				if (!this.productDetail) return '加载中...';
				
				switch (this.productDetail.status) {
					case 'active':
						return '立即报名';
					case 'inactive':
						return '活动已结束';
					case 'pending':
						return '审核中';
					default:
						return '立即报名';
				}
			},
			
			// 切换收藏状态
			toggleFavorite() {
				this.isFavorite = !this.isFavorite;
				uni.showToast({
					title: this.isFavorite ? '已收藏' : '已取消收藏',
					icon: 'success'
				});
			},
			
			// 联系客服
			contactService() {
				if (this.productDetail && this.productDetail.contactPhone) {
					uni.makePhoneCall({
						phoneNumber: this.productDetail.contactPhone,
						success: () => {
							console.log('拨打电话成功');
						},
						fail: (err) => {
							console.error('拨打电话失败:', err);
							uni.showToast({
								title: '拨打电话失败',
								icon: 'none'
							});
						}
					});
				} else {
					uni.showToast({
						title: '暂无客服电话',
						icon: 'none'
					});
				}
			},
			
			// 参与团购
			async joinGroup() {
				if (!this.productDetail || this.productDetail.status !== 'active') {
					uni.showToast({
						title: '活动已结束或不可用',
						icon: 'none'
					});
					return;
				}
				
				uni.showModal({
					title: '确认报名',
					content: `确定要报名"${this.productDetail.title}"的活动吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '报名中...' });
								
								// 使用新的API接口参与团购
								const result = await groupPurchaseApi.joinGroupPurchase(this.productDetail.id, 1); // 暂时使用用户ID 1
								
								if (result && result.code === 200) {
									uni.showToast({
										title: '报名成功！',
										icon: 'success'
									});
									
									// 更新参与人数
									this.productDetail.currentParticipants++;
								} else {
									uni.showToast({
										title: result?.msg || '报名失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('报名失败:', error);
								uni.showToast({
									title: '报名失败，请重试',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.group-buy-detail-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 80px;
	}
	
	// 加载状态
	.loading-container {
		padding: 20px;
		text-align: center;
		background-color: #ffffff;
		margin: 12px;
		border-radius: 8px;
	}
	
	// 自定义导航栏
	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 44px 16px 12px 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
		
		.navbar-left {
			width: 40px;
		}
		
		.navbar-title {
			font-size: 18px;
			font-weight: bold;
			color: #333333;
		}
		
		.navbar-right {
			width: 40px;
			display: flex;
			justify-content: flex-end;
		}
	}
	
	// 商品图片轮播
	.product-images {
		background-color: #ffffff;
		margin-bottom: 12px;
		
		.image-swiper {
			height: 300px;
			
			.product-image {
				width: 100%;
				height: 100%;
			}
		}
	}
	
	// 商品基本信息
	.product-info {
		background-color: #ffffff;
		padding: 16px;
		margin-bottom: 12px;
		
		.product-title {
			font-size: 18px;
			font-weight: bold;
			color: #333333;
			margin-bottom: 12px;
		}
		
		.product-meta {
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.publisher {
				font-size: 14px;
				color: #666666;
			}
			
			.publish-time {
				font-size: 12px;
				color: #999999;
			}
		}
	}
	
	// 活动描述
	.activity-description {
		background-color: #ffffff;
		padding: 16px;
		margin-bottom: 12px;
		
		.description-text {
			font-size: 14px;
			color: #666666;
			line-height: 1.6;
			margin-bottom: 12px;
			
			&:last-child {
				margin-bottom: 0;
			}
		}
	}
	
	// 价格信息
	.price-info {
		background-color: #ffffff;
		padding: 16px;
		margin-bottom: 12px;
		
		.price-section {
			display: flex;
			align-items: center;
			margin-bottom: 8px;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.price-label {
				font-size: 14px;
				color: #666666;
				margin-right: 8px;
			}
			
			.current-price {
				font-size: 16px;
				font-weight: bold;
				color: #ff4757;
			}
			
			.original-price {
				font-size: 14px;
				color: #999999;
				text-decoration: line-through;
			}
			
			.discount-text {
				font-size: 14px;
				color: #ff4757;
				font-weight: bold;
			}
		}
	}
	
	// 活动详情
	.activity-details {
		background-color: #ffffff;
		padding: 16px;
		margin-bottom: 12px;
		
		.detail-item {
			display: flex;
			margin-bottom: 8px;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.detail-label {
				font-size: 14px;
				color: #666666;
				width: 80px;
				flex-shrink: 0;
			}
			
			.detail-value {
				font-size: 14px;
				color: #333333;
				flex: 1;
			}
			
			.debug-info {
				font-size: 10px;
				color: #999999;
				margin-left: 8px;
				font-style: italic;
			}
		}
	}

	
	// 底部操作栏
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		padding: 12px 16px;
		background-color: #ffffff;
		border-top: 1px solid #f0f0f0;
		
		.action-left {
			display: flex;
			gap: 24px;
			
			.action-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 4px;
				
				.action-text {
					font-size: 10px;
					color: #666666;
				}
			}
		}
		
		.action-right {
			flex: 1;
			margin-left: 16px;
			
			.join-btn {
				background-color: #007AFF;
				padding: 12px;
				border-radius: 8px;
				text-align: center;
				
				&.disabled {
					background-color: #ccc;
					color: #888;
					pointer-events: none;
				}
				
				.btn-text {
					font-size: 16px;
					color: #ffffff;
					font-weight: bold;
				}
			}
		}
	}
	
	// 错误提示
	.error-container {
		padding: 20px;
		text-align: center;
		background-color: #ffffff;
		margin: 12px;
		border-radius: 8px;
		
		.error-text {
			color: #ff4757;
			font-size: 14px;
			margin-bottom: 10px;
			display: block;
		}
		
		.retry-btn {
			margin-top: 10px;
			padding: 8px 15px;
			background-color: #007AFF;
			color: #ffffff;
			border-radius: 8px;
			font-size: 14px;
			display: inline-block;
			cursor: pointer;
		}
	}
</style> 